package cn.wildfirechat.app.second.controller;

import cn.wildfirechat.app.common.ZlAPIPath;
import cn.wildfirechat.app.jpa.*;
import cn.wildfirechat.app.model.PrepayRequest;
import cn.wildfirechat.app.pojo.PointsConingResponse;
import cn.wildfirechat.app.pojo.ReportRequest;
import cn.wildfirechat.app.pojo.RewardPointsRequest;
import cn.wildfirechat.app.pojo.UserSendGroupMessageRequest;
import cn.wildfirechat.app.second.service.ZlService;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Slf4j
@RestController
@RequestMapping("/zl")
public class ZlController {
    @Value("${zl.query_protocol_url}")
    private String findsSafetyUrl;
    @Value("${zl.query_protocol_anquan_key}")
    private String anquanKey;
    @Value("${zl.query_protocol_user_xieyi_key}")
    private String userXieYiKey;
    @Value("${zl.query_protocol_yinsi_xieyi_key}")
    private String yinsiXieYiKey;
    @Value("${zl.query_protocol_anquan_xieyi_key}")
    private String anQuanXieYiKey;
    @Value("${zl.add_report_url}")
    private String addReportUrl;
    @Value("${zl.get_reportType_url}")
    private String getReportTypeUrl;
    @Value("${zl.user_send_group_message}")
    private String userSendGroupMessageUrl;
    @Value("${zl.get_user_send_group_message_history_url}")
    private String getUserSendGroupMessageHistoryUrl;
    @Value("${zl.delete_history_url}")
    private String deleteHistoryUrl;

    @Autowired
    private ZlService zlService;

    @Autowired
    private UserPointsRepository userPointsRepository;
    @Autowired
    private PointsConfigDetailRepository pointsConfigDetailRepository;
    @Autowired
    private PointsConfigRepository pointsConfigRepository;
    @Autowired
    private UserPointsLogRepository userPointsLogRepository;
    @Autowired
    private PostsRepository postsRepository;

    /**
     * 查询配置
     * @param type
     * @return
     */
    @GetMapping(value = "/find/safety/{type}", produces = "application/json;charset=UTF-8")
    public Object findsSafety(@PathVariable String type) {
        String key = "";
        switch (type){
            case "1":key = anquanKey; break;
            case "2":key = userXieYiKey; break;
            case "3":key = yinsiXieYiKey; break;
            case "4":key = anQuanXieYiKey; break;
            default:
                key = type;
        }
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(findsSafetyUrl+key);
            try (CloseableHttpResponse resp = client.execute(get)) {
                if (resp.getStatusLine().getStatusCode() == 200){
                    String string = EntityUtils.toString(resp.getEntity(), "UTF-8");
                    Map<String, Object> resultMap = new ObjectMapper().readValue(string, Map.class);
                    return resultMap.get("data");
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }

        return null;
    }

    /**
     * 新增举报
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping(value = "/report/add", produces = "application/json;charset=UTF-8")
    public Object addReport(@RequestBody ReportRequest request) throws JsonProcessingException {
        // 发送http请求到举报服务
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            ObjectMapper mapper = new ObjectMapper();
            request.setUserId(userId);
            String json = mapper.writeValueAsString(request);
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost post = new HttpPost(addReportUrl);
                post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
                try (CloseableHttpResponse resp = client.execute(post)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return true;
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 获取举报类型
     * @return
     */
    @GetMapping(value = "/getReportType", produces = "application/json;charset=UTF-8")
    public Object getReportType() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(getReportTypeUrl);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
//                        String string = EntityUtils.toString(resp.getEntity(), "UTF-8");
//                        Map<String, Object> resultMap = new ObjectMapper().readValue(string, Map.class);
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 群发助手功能
     * @return
     */
    @PostMapping(value = "/userSendGroupMessage", produces = "application/json;charset=UTF-8")
    public Object userSendGroupMessage(@RequestBody UserSendGroupMessageRequest message) {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            ObjectMapper mapper = new ObjectMapper();
            String json = null;
            try {
                json = mapper.writeValueAsString(message);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost post = new HttpPost(userSendGroupMessageUrl);
                post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
                try (CloseableHttpResponse resp = client.execute(post)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return true;
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 群发助手功能消息历史记录
     * @return
     */
    @GetMapping(value = "/getUserSendGroupMessageHistory/{id}", produces = "application/json;charset=UTF-8")
    public Object getUserSendGroupMessageHistory(@PathVariable String id) {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(getUserSendGroupMessageHistoryUrl+"/"+id);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }



    /**
     * 删除群发助手功能消息历史记录
     * @return
     */
    @GetMapping(value = "/deleteHistory/{id}", produces = "application/json;charset=UTF-8")
    public Object deleteHistory(@PathVariable String id) {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(deleteHistoryUrl+"/"+id);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 当前用户的会员权限
     * @return
     */
    @GetMapping(value = "/checkGroupHelper", produces = "application/json;charset=UTF-8")
    public Object checkGroupHelper() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(ZlAPIPath.checkGroupHelperUrl+"/"+userId);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }


    /**
     * pc端权限校验
     * @return
     */
    @GetMapping(value = "/pcLoginCheck/{mobile}", produces = "application/json;charset=UTF-8")
    public Object PcLoginCheck(@PathVariable String mobile) {
        if (!StringUtils.isEmpty(mobile)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(ZlAPIPath.PcLoginCheckUrl +"/"+mobile);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 加好友权限校验
     * @return
     */
    @GetMapping(value = "/addFriendCheck", produces = "application/json;charset=UTF-8")
    public Object addFriendCheck() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(ZlAPIPath.addFriendCheck+"/"+userId);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }



    /**
     * 会员配置页面
     * @return
     */
    @GetMapping(value = "/getMemberList", produces = "application/json;charset=UTF-8")
    public Object memberList() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(ZlAPIPath.MemberConfigListUrl+"?pageNum=1&pageSize=1000&state=1&userId="+userId);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }


    /**
     * 购买订单记录页面
     * @return
     */
    @GetMapping(value = "/getOrderList", produces = "application/json;charset=UTF-8")
    public Object getOrderList() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet(ZlAPIPath.MemberOrderListUrl+"?pageNum=1&pageSize=1000&userId="+userId);
                try (CloseableHttpResponse resp = client.execute(get)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }
    /**
     * 用户会员权益分类信息
     * @throws Exception
     */
    @PostMapping(value = "/getUserMemberInfo", produces = "application/json;charset=UTF-8")
    public Object getUserMemberInfo() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            return zlService.getUserMemberInfo(userId);
        }
        return null;
    }


    /** 安卓/iOS/鸿蒙 统一获取调起参数 */
    @PostMapping("/preCreate")
    public Object preCreate(@RequestBody PrepayRequest dto){
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            ObjectMapper mapper = new ObjectMapper();
            String json = null;
            try {
                json = mapper.writeValueAsString(dto);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost post = new HttpPost(ZlAPIPath.CreateOrderUrl);
                post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
                try (CloseableHttpResponse resp = client.execute(post)) {
                    if (resp.getStatusLine().getStatusCode() == 200){
                        return EntityUtils.toString(resp.getEntity(), "UTF-8");
                    }
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 个人积分
     * @throws Exception
     */
    @GetMapping(value = "/getUserPoints", produces = "application/json;charset=UTF-8")
    public Object getUserPoints() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            // 查询用户积分
            return zlService.getUserPoints(userId);
        }
        return null;
    }


    /**
     * 个人积分日志
     * @throws Exception
     */
    @GetMapping(value = "/getUserPointsLog", produces = "application/json;charset=UTF-8")
    public Object getUserPointsLog() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            // 查询个人积分日志
            return zlService.getUserPointsLog(userId);
        }
        return null;
    }

    /**
     * 积分配置查询
     * @throws Exception
     */
    @GetMapping(value = "/getPointsConing", produces = "application/json;charset=UTF-8")
    public Object getPointsConing() {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            return  zlService.getPointsConing();
        }
        return null;
    }

    /**
     * 积分打赏
     * @throws Exception
     */
    @PostMapping(value = "/rewardPoints", produces = "application/json;charset=UTF-8")
    public Object rewardPoints(@RequestBody RewardPointsRequest request) {
        Subject subject = SecurityUtils.getSubject();
        String userId = (String) subject.getSession().getAttribute("userId");
        if (!StringUtils.isEmpty(userId)){
            return zlService.rewardPoints(userId,request);
        }
        return null;
    }



















    public static void main(String[] args) throws Exception {

        try (CloseableHttpClient client = HttpClients.createDefault()) {


            HttpGet get = new HttpGet("http://localhost:7080/system/config/configKeyByApp/1");
            try (CloseableHttpResponse resp = client.execute(get)) {
                if (resp.getStatusLine().getStatusCode() == 200) {
                    String string = EntityUtils.toString(resp.getEntity(), "UTF-8");
                    Map<String, Object> resultMap = new ObjectMapper().readValue(string, Map.class);
                    System.out.println(resultMap.get("data"));
                }
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
